<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
require_once __DIR__ . '/../../../tools/tools.logger.php';

logger()->log_path = __DIR__ . '/log';

class Events
{
   
   /**
    * 有消息时
    * @param int $client_id
    * @param mixed $message
    */
   public static function onMessage($client_id, $message)
   {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";
        
        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            return ;
        }
        
        // 根据类型执行不同的业务
        switch($message_data['type'])
        {
            // 客户端回应服务端的心跳
            case 'pong':
                if (isset($_SESSION['群id']) and isset($_SESSION['userId'])) {
                    $sql = sprintf("update `群离线` set  `is_online` = 1 where `用户id` = '%s' and `群id` = '%s'",                                $_SESSION['userId'], $_SESSION['群id']);
                    $row_count = Db::instance('db1')->query($sql);
                }

                return;
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'login':
                // 判断是否有房间号
                if(!isset($message_data['群id']))
                {
                    throw new \Exception("\$message_data['群id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }

                // 把房间号昵称放到session中
                $群id = $message_data['群id'];
                $username = htmlspecialchars($message_data['username']);
                $_SESSION['群id'] = $群id;
                $_SESSION['userId'] = $message_data['userid'];
                $_SESSION['username'] = $username;
                $_SESSION['login_time'] = time();

                Gateway::joinGroup($client_id, $群id);
                $new_message = array('type'=>'login', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['username'], 'time'=>date('Y-m-d H:i:s'));
                Gateway::sendToGroup($群id, json_encode($new_message));

                logger()->logInfo(sprintf("进入聊天，client_id:%s, 群id:%s, username:%s", $client_id,$群id,$username));
                return;
                
            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'usermsg':
                // 非法请求
                if(!isset($_SESSION['群id']))
                {
                    throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                $群id = $_SESSION['群id'];
                $username = $_SESSION['username'];

                Gateway::sendToGroup($群id ,json_encode($message_data));
                return;
        }
   }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {
       // debug
       echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
       
       // 从房间的客户端列表中删除
       if(isset($_SESSION['群id'])) {
           $群id = $_SESSION['群id'];
           $userId = $_SESSION['userId'];
           $new_message = array('type'=>'logout', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['username'], 'time'=>date('Y-m-d H:i:s'));
           Gateway::sendToGroup($群id, json_encode($new_message));
           $db_re = self::dbOutGroup($群id, $userId);
           logger()->logInfo(sprintf("==离开聊天，client_id:%s, 群id:%s, username:%s",
               $client_id,$群id,$_SESSION['username']));
       }
   }

    public static function dbOutGroup($groupId, $userId) {

        $time_length = time() - $_SESSION['login_time'];
        $sql = sprintf("update `群离线`
                set `最后在线时间` = '%s', `time_length` = `time_length` + '%s', `is_online` = 0
                where `用户id` = '%s' and `群id` = '%s'", date("Y-m-d H:i:s"), $time_length, $userId, $groupId);

        logger()->logInfo($sql);
        $db1 = Db::instance('db1');
        $row_count = $db1->query($sql);
        return $row_count;
    }
  
}
